//
//  statusPictureView.swift
//  NSinaWeibo
//
//  Created by LoliQueen on 16/2/22.
//  Copyright © 2016年 LoliQueen. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class statusPictureView: UICollectionView {
    
    let cellID = "cellID"
    
    ///图片地址数组属性,给数组赋值的同时，计算statusPictureView的大小
    var pictureUrls : [NSURL]?{
        didSet{
        let size = calculateStatusPictureViewSize()
            //更新statusPictureView的大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            reloadData()
            
            //给图片数量label赋值
            picCountLabel.text = "\(pictureUrls?.count ?? 0)"
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        //实例化流水布局视图
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        //设置layout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //设置最想间距
        flowLayout.minimumInteritemSpacing = picMargin
        flowLayout.minimumLineSpacing = picMargin
        
        //注册cell，设置数据源
        self.registerClass(pictureCell.self, forCellWithReuseIdentifier: cellID)
        self.dataSource = self
        
         self.backgroundColor = UIColor.whiteColor()
         //点击状态栏： 如果同一页面，有超过一个scrollerView,或集成crollerView的控件，需要关闭一个，否则两都不能实现。
        self.scrollsToTop = false
        setUpUI()
    }
    
    private func setUpUI(){
        //添加label到视图上
        self.addSubview(picCountLabel)
        picCountLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    let itemWidth = (ScreenWidth - picMargin*2 - homeVCMargin*2)/3
    ///根据图片的数量来，计算配图视图的真实大小
    private func calculateStatusPictureViewSize() -> CGSize{
        //获取图片数量
        let imageCount = pictureUrls?.count ?? 0
        if imageCount == 0{
            return CGSizeZero
        }
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if imageCount == 1{
            let imageSize = CGSize(width: 150, height: 250)
            layout.itemSize = imageSize
            return imageSize
        }
        ///如果不是单张图片，重新设置图片的大小，避免复用
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        
        if imageCount == 4{
            let w = picMargin*2 + itemWidth*2
            return CGSize(width: w, height: w)
        }
        
        /*
            1,2,3 --- 1
            4,5,6 --- 2
            7,8,9 --- 3
        */
        
        //其他情况
        //计算出行数
        let row = CGFloat((imageCount-1) / 3 + 1)
        //至少占一行 所以宽度固定
        let w = itemWidth * 3 + picMargin * 2
        let h = itemWidth * row + (row - 1) * picMargin

        return CGSize(width: w, height: h)
        
        
    }
    
    
    
    ///图片数量
    lazy var picCountLabel : UILabel = UILabel(title: "", textSize: 40, textColor: UIColor.yellowColor())
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}




///数据源方法
extension statusPictureView: UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! pictureCell
        cell.backgroundColor = indexPath.row%2 == 0 ? UIColor.redColor() : UIColor.blueColor()
        cell.imageUrl = pictureUrls![indexPath.item]
        
        return cell
    }
    
}

private class pictureCell: UICollectionViewCell {
    
    ///图片地址属性
    var imageUrl: NSURL? {
        //根据地址，加载图片
        didSet{
            iconImageView.sd_setImageWithURL(imageUrl)
        }
    
    }
    ///重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(white: 0.9, alpha: 1)
        //添加子控件到cell上
        contentView.addSubview(iconImageView)
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
            
             //点击状态栏： 如果同一页面，有超过一个scrollerView,或集成crollerView的控件，需要关闭一个，否则两都不能实现。
        
        }
    }
    
    
    //懒加载图片视图
    lazy var iconImageView : UIImageView = {
        let icon = UIImageView()
        //UIImageView默认的显示方式  ScaleToFill: 缩放全部视图进行填充
        // Aspect: 部分  缩放部分 进行填充  视图的比例不会失真 但是 图片会被裁剪
        icon.contentMode = .ScaleAspectFill
        //手动设置裁剪
        icon.clipsToBounds = true
        return icon
        }()
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}